package com.zb.rebbitMq;


import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

public class Producer3 {

	private static final String QUEUE_INFORM_EMAIL ="queue_inform_email";
	private static final String QUEUE_INFORM_SMS ="queue_inform_sms";
	private static final String EXCHANGE_FANOUT_INFORM ="exchange_fanout_inform";
	private static final String ROUTING_KEY_EMAIL = "email";
	private Connection connection =null;
	private Channel channel = null;
	
	private static final ConnectionFactory factory = new ConnectionFactory();
	
	
	public Producer3() {
		
		factory.setHost("106.12.222.85");
		factory.setPort(5672);
		factory.setUsername("guest");
		factory.setPassword("guest");
		factory.setVirtualHost("/");
		
	}
	
	
	public void send() {
		
		//连接
		try {
	    connection = factory.newConnection();
		channel = connection.createChannel();
		
		//申明队列
		channel.queueDeclare(QUEUE_INFORM_EMAIL, false, false, false, null);
		channel.queueDeclare(QUEUE_INFORM_SMS, false, false, false, null);
		
		//申明交换机
		channel.exchangeDeclare(EXCHANGE_FANOUT_INFORM, BuiltinExchangeType.DIRECT);
		
		
		
		//交换机和队列进行绑定
		channel.queueBind(QUEUE_INFORM_EMAIL, EXCHANGE_FANOUT_INFORM, ROUTING_KEY_EMAIL);
		channel.queueBind(QUEUE_INFORM_SMS, EXCHANGE_FANOUT_INFORM, "");
		
		for(int i =0;i<5;i++) {
		String message ="send message to user";
		//发布消息
		channel.basicPublish(EXCHANGE_FANOUT_INFORM, ROUTING_KEY_EMAIL, null, message.getBytes());
		System.out.println(message);
		
		}
		
		}catch (Exception e) {
			// TODO: handle exception
		}finally {
			try {
				 channel.close();
				 connection.close();
			}catch (Exception e) {
				// TODO: handle exception
			}  
			
		}
		
	}
	
	public static void main(String[] args) {
		Producer3 producer3 = new Producer3();
		producer3.send();
	}
}
